package com.yjhb.android.sbz.fragment;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.yjhb.android.sbz.App;
import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.BiddingActivity;
import com.yjhb.android.sbz.activity.BondMoneyActivity;
import com.yjhb.android.sbz.activity.BusinessActivity;
import com.yjhb.android.sbz.activity.FeedbackActivity;
import com.yjhb.android.sbz.activity.IMActivity;
import com.yjhb.android.sbz.activity.LoginActivity;
import com.yjhb.android.sbz.activity.ManageTaskActivity;
import com.yjhb.android.sbz.activity.MoneyBalanceActivity;
import com.yjhb.android.sbz.activity.MoneyRewardActivity;
import com.yjhb.android.sbz.activity.MyFollowActivity;
import com.yjhb.android.sbz.activity.MyInviterActivity;
import com.yjhb.android.sbz.activity.MyTaskActivity;
import com.yjhb.android.sbz.activity.RefreshPackageActivity;
import com.yjhb.android.sbz.activity.ReputationActivity;
import com.yjhb.android.sbz.activity.SettingActivity;
import com.yjhb.android.sbz.activity.SettingInfoActivity;
import com.yjhb.android.sbz.activity.TipOffActivity;
import com.yjhb.android.sbz.activity.VipCenterActivity;
import com.yjhb.android.sbz.entity.AdBanner;
import com.yjhb.android.sbz.entity.UserInfo;
import com.yjhb.android.sbz.mvp.my.MyPresenter;
import com.yjhb.android.sbz.mvp.my.MyView;
import com.yjhb.android.sbz.tool.EventMsg;
import com.yjhb.android.sbz.tool.LoadingDialogTool;
import com.yjhb.android.sbz.tool.Tool;
import com.yjhb.android.sbz.v2.activity.PromotionRewardActivityV2;
import com.yjhb.android.sbz.v2.activity.UserRewardActivityV2;
import com.yjhb.android.sbz.v2.activity.V2InviteFriendActivity;
import com.yjhb.android.sbz.v2.activity.V2VipActivity;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.jojo.android.zxlib.view.CircleImageView;
import com.jojo.android.zxlib.view.dialog.ILoading;
import com.tencent.qcloud.tim.uikit.Observer;
import com.tencent.qcloud.tim.uikit.UnReadManager;
import com.tencent.qcloud.tim.uikit.modules.conversation.ConversationManagerKit;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.loader.ImageLoaderInterface;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 创建者 zx
 * 创建时间 2020/11/17 16:47
 */
public class MyFragment extends BaseFragment<MyPresenter> implements Observer<Integer>, MyView, SwipeRefreshLayout.OnRefreshListener {
    private final String TAG = "MyFragment";

    @BindView(R.id.my_head_iv)
    CircleImageView my_head_iv;
    @BindView(R.id.vip_flag)
    ImageView vip_flag;
    @BindView(R.id.my_name_tv)
    TextView my_name_tv;
    @BindView(R.id.my_id_tv)
    TextView my_id_tv;
    @BindView(R.id.fraction_tv)
    TextView fraction_tv;
    @BindView(R.id.progressbar1)
    ProgressBar progressbar1;
    @BindView(R.id.unLoginView)
    FrameLayout unLoginView;
    @BindView(R.id.msg_unread_tv)
    TextView msg_unread_tv;
    @BindView(R.id.report_unread_tv)
    TextView report_unread_tv;
    @BindView(R.id.swipe_recyclerview)
    SwipeRefreshLayout swipe_recyclerview;
    @BindView(R.id.vip)
    TextView vip;
    @BindView(R.id.income_tv)
    TextView incomeTv;
    @BindView(R.id.balance_tv)
    TextView balanceTv;
    @BindView(R.id.bond_tv)
    TextView bondTv;
    @BindView(R.id.my_banner)
    Banner my_banner;

    private ILoading loading;
    private List<AdBanner> adBanners;

    @Override
    protected MyPresenter initPresenter() {
        return new MyPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my2;
    }

    @Override
    protected void initUI() {
        loading = LoadingDialogTool.createDialog(this);
        update();

    }


    @Override
    protected void initData() {
        presenter.getBanner();
    }

    @Override
    protected void initEvent() {
        swipe_recyclerview.setColorSchemeColors(getResources().getColor(R.color.colorPrimary),
                getResources().getColor(R.color.colorPrimaryDark),
                getResources().getColor(R.color.colorPrimaryOtherDark));
        swipe_recyclerview.setOnRefreshListener(this);
        EventBus.getDefault().register(this);
        UnReadManager.getInstance().register(this);
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        UnReadManager.getInstance().unregister(this);
        super.onDestroy();
    }

    /**
     * 初始化广告位
     */
    private void initBanner(List<AdBanner> images) {
//        List<Integer> imagIds = new ArrayList<>();
//        imagIds.add(R.mipmap.my_ad);
//        imagIds.add(R.mipmap.my_ad2);
//        imagIds.add(R.mipmap.vip_banner);
        my_banner.setImages(images);
        my_banner.setImageLoader(new ImageLoaderInterface() {
            @Override
            public void displayImage(Context context, Object path, View imageView) {
                if (path instanceof Integer) {
                    //占满、不剪切
                    ((ImageView) imageView).setScaleType(ImageView.ScaleType.FIT_XY);
                    ((ImageView) imageView).setImageResource((Integer) path);
                } else if (path instanceof AdBanner) {
                    Glide.with(context).load(((AdBanner) path).getBanner())
//                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(ZxTool.dip2px(3))))
                            .into((ImageView) imageView);
                }
            }

            @Override
            public View createImageView(Context context) {
                ImageView img = new ImageView(context);
                img.setScaleType(ImageView.ScaleType.FIT_XY);
                return img;
            }
        });
        my_banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);  //设置banner样式
        my_banner.setBannerAnimation(Transformer.Default); //设置banner动画效果
        my_banner.setDelayTime(3000);
        my_banner.setIndicatorGravity(BannerConfig.CENTER);
        my_banner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                position = position - 1;
                if (adBanners != null && adBanners.size() > position) {
                    AdBanner adBanner = adBanners.get(position);
                    //type ==0 跳网页  type == 1 跳APP页面 type == 2 不做操作
                    if (adBanner.getType() == 0) {
                        Tool.startWebActivity(getContext(), adBanner.getContent(), adBanner.getTitle());
                    } else if (adBanner.getType() == 1) {
                        if (!TextUtils.isEmpty(adBanner.getContent())) {
                            switch (adBanner.getContent()) {
                                case "推广奖励":
                                    ZxActivityTool.skipActivity(getContext(), PromotionRewardActivityV2.class);
                                    break;
                                case "赚":
                                    ZxActivityTool.skipActivity(getContext(), V2InviteFriendActivity.class);
                                    break;
                                case "任务大奖":
                                    ZxActivityTool.skipActivity(getContext(), UserRewardActivityV2.class);
                                    break;
                                case "游戏":
                                    EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT, 3));
                                    break;
                                case "会员":
                                    startActivity(new Intent(getContext(), VipCenterActivity.class));
                                    break;
                            }
                        }
                    }
                }
            }
        });
        my_banner.start();
    }

    @Override
    public void update(int type, Integer arg) {
//        if (type == UnReadManager.TYPE_MSG || type == UnReadManager.TYPE_SYS) {
//            int total = UnReadManager.getInstance().getUnreadMsg() +
//                    UnReadManager.getInstance().getUnreadSys();
//            if (total > 0) {
//                msg_unread_tv.setText("" + total);
//                msg_unread_tv.setVisibility(View.VISIBLE);
//            } else {
//                msg_unread_tv.setVisibility(View.GONE);
//            }
//        }
//        if (type == UnReadManager.TYPE_REPORT) {
//            int total = UnReadManager.getInstance().getUnreadReport();
//            if (total > 0) {
//                report_unread_tv.setText("" + total);
//                report_unread_tv.setVisibility(View.VISIBLE);
//            } else {
//                report_unread_tv.setVisibility(View.GONE);
//            }
//        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsg(EventMsg msg) {
        if (msg.msg == EventMsg.USER_UPDATE_OK) {
            update();
        }
    }

    @Override
    public void onUserVisibleChanged(boolean visible) {
        if (visible)
            onRefresh();
        super.onUserVisibleChanged(visible);
    }

    private void update() {
        swipe_recyclerview.setRefreshing(false);
        UserInfo userInfo = App.userInfo;
        if (userInfo != null) {
            unLoginView.setVisibility(View.GONE);
            Glide.with(this).load(userInfo.getAvatar()).apply(new RequestOptions().placeholder(R.mipmap.test_head)).into(my_head_iv);
            my_name_tv.setText(userInfo.getNickName());
            my_id_tv.setText("ID:" + userInfo.getId());
            progressbar1.setMax(Tool.getMaxScore(userInfo.getScore()));
            progressbar1.setProgress(userInfo.getScore());
            fraction_tv.setText(userInfo.getScore() + "/" + (userInfo.getScore() < 0 ? 0 : Tool.getMaxScore(userInfo.getScore())));
            incomeTv.setText("" + Tool.getPrettyNumber(new BigDecimal(userInfo.getEarnMoney())));
            balanceTv.setText("" + Tool.getPrettyNumber(new BigDecimal(userInfo.getPayMoney())));
            bondTv.setText("" + Tool.getPrettyNumber(new BigDecimal(userInfo.getCreditMoney())));
            int vipLevel = userInfo.getVipLevel();
            vip_flag.setVisibility(View.VISIBLE);
            switch (vipLevel) {
                case 100:
                    vip.setText("体验会员");
                    vip_flag.setImageResource(R.mipmap.exp);
                    break;
                case 1:
                    vip.setText("月度会员");
                    vip_flag.setImageResource(R.mipmap.month);
                    break;
                case 2:
                    vip.setText("季度会员");
                    vip_flag.setImageResource(R.mipmap.season);
                    break;
                case 3:
                    vip.setText("年度会员");
                    vip_flag.setImageResource(R.mipmap.year);
                    break;
                case 4:
                    vip.setText("半年会员");
                    vip_flag.setImageResource(R.mipmap.half_year);
                    break;
                default:
                    vip.setText("开通会员");
                    vip_flag.setVisibility(View.GONE);
            }
        } else {
            unLoginView.setVisibility(View.VISIBLE);
            unLoginView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });
        }
        update(UnReadManager.TYPE_MSG, UnReadManager.getInstance().getUnreadMsg());
        update(UnReadManager.TYPE_CHECK, UnReadManager.getInstance().getUncheck());
        update(UnReadManager.TYPE_REPORT, UnReadManager.getInstance().getUnreadReport());
    }

    @OnClick({R.id.setting_iv, R.id.setting})
    void setting_iv() {
        startActivity(new Intent(getContext(), SettingActivity.class));
    }


    @OnClick(R.id.publish_task_layout)
    void publish_task_layout() {
        startActivity(new Intent(getContext(), ManageTaskActivity.class));
    }

    @OnClick(R.id.invite_friend)
    void invite_friend() {
        startActivity(new Intent(getContext(), V2InviteFriendActivity.class));
    }

    @OnClick(R.id.my_head_iv)
    void my_head_iv() {
        startActivity(new Intent(getContext(), SettingInfoActivity.class));
    }

    @OnClick(R.id.myDianpu)
    void myDianpu() {
        if (App.userInfo.getId() != null)
            Tool.startUserInfoActivity(getContext(), Integer.parseInt(App.userInfo.getId()));
    }

    @OnClick(R.id.go_balance_tv)
    void balance_layout() {
        startActivity(new Intent(getContext(), MoneyRewardActivity.class));
    }

    @OnClick(R.id.go_income_tv)
    void income_layout() {
        startActivity(new Intent(getContext(), MoneyBalanceActivity.class));
    }

    @OnClick(R.id.refresh_package_item)
    void refresh_package_item() {
        startActivity(new Intent(getContext(), RefreshPackageActivity.class));
    }

    @OnClick(R.id.my_invi)
    void my_invi() {
        ZxActivityTool.skipActivity(getContext(), V2InviteFriendActivity.class);
//        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_MAIN_SWITCH_FRAGMENT, 2));
    }

    @OnClick(R.id.vip)
    void vip_layout() {
        startActivity(new Intent(getContext(), V2VipActivity.class));
    }

    @OnClick(R.id.go_bond_tv)
    void bond_layout() {
        startActivity(new Intent(getContext(), BondMoneyActivity.class));
    }

    @OnClick(R.id.bidding_layout)
    void bidding_layout() {
        startActivity(new Intent(getContext(), BiddingActivity.class));
    }

    @OnClick(R.id.my_task)
    void my_task() {
        startActivity(new Intent(getContext(), MyTaskActivity.class));
    }

    @OnClick(R.id.tipOff)
    void tipOff() {
        startActivity(new Intent(getContext(), TipOffActivity.class));
    }

    @OnClick(R.id.login_tv)
    void login_tv() {
        startActivity(new Intent(getContext(), LoginActivity.class));
    }

    @OnClick(R.id.myMessage)
    void myMessage() {
        startActivity(new Intent(getContext(), IMActivity.class));
    }

    @OnClick(R.id.content_tv)
    void contactKefu() {
//        presenter.getCustomerService();
        Tool.startChatActivity(getContext(), " ", "在线客服", 3);
    }

    @OnClick(R.id.feedback)
    void feedback() {
        ZxActivityTool.skipActivity(getContext(), FeedbackActivity.class);
    }

    @OnClick(R.id.reputation)
    void reputation() {
        ZxActivityTool.skipActivity(getContext(), ReputationActivity.class);
    }

    @OnClick(R.id.my_inviter)
    void my_inviter() {
        ZxActivityTool.skipActivity(getContext(), MyInviterActivity.class);
    }

    @OnClick(R.id.myFollow)
    void myFollow() {
        ZxActivityTool.skipActivity(getContext(), MyFollowActivity.class);
    }

    @OnClick(R.id.business)
    void business() {
        ZxActivityTool.skipActivity(getContext(), BusinessActivity.class);
    }


    @Override
    public void onFailure(int code, String msg) {
        ZxToast.showINFOBottomToast(msg);
        swipe_recyclerview.setRefreshing(false);
        loading.cancel();
    }

    @Override
    public void onWait(String tips) {
        loading.setTipsText(tips);
        loading.show();
    }

    @Override
    public void onCustomerService(String id) {
        loading.cancel();
        Tool.startChatActivity(getContext(), id, "在线客服", 3);
    }

    @Override
    public void onBanner(List<AdBanner> adBanners) {
        this.adBanners = adBanners;
        initBanner(adBanners);
    }


    @Override
    public void onRefresh() {
        ConversationManagerKit.getInstance().loadConversation(null);
        EventBus.getDefault().post(new EventMsg(EventMsg.REQUEST_USER_UPDATE, null));
    }
}
